const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  
  try {
    const { mealId, quantity = 1 } = event
    
    if (!mealId) {
      return {
        success: false,
        errMsg: '套餐ID不能为空'
      }
    }

    // 获取套餐信息
    const mealResult = await db.collection('meals')
      .doc(mealId)
      .get()

    if (!mealResult.data) {
      return {
        success: false,
        errMsg: '套餐不存在'
      }
    }

    const meal = mealResult.data

    // 创建订单
    const orderData = {
      userId: OPENID,
      mealId: mealId,
      mealName: meal.name,
      mealImage: meal.image,
      quantity: quantity,
      price: meal.price,
      totalAmount: meal.price * quantity,
      status: 'pending', // pending, paid, completed, cancelled
      createTime: db.serverDate(),
      updateTime: db.serverDate(),
      // 订单其他信息
      nutritionInfo: {
        calories: meal.calories * quantity,
        protein: meal.protein * quantity,
        carbs: meal.carbs * quantity,
        fat: meal.fat * quantity
      }
    }

    const orderResult = await db.collection('orders').add({
      data: orderData
    })

    if (!orderResult._id) {
      throw new Error('创建订单失败')
    }

    // 更新用户订单统计
    await db.collection('users').where({
      _openid: OPENID
    }).update({
      data: {
        orderCount: _.inc(1),
        totalSpent: _.inc(orderData.totalAmount),
        lastOrderTime: orderData.createTime
      }
    })

    return {
      success: true,
      orderId: orderResult._id,
      orderData: {
        ...orderData,
        _id: orderResult._id
      }
    }

  } catch (error) {
    console.error('创建订单失败:', error)
    return {
      success: false,
      errMsg: error.message || '创建订单失败'
    }
  }
} 